

class Node {
    constructor(ele, next) {
        this.ele = ele
        this.next = next
    }
}

class LinkedList {
    constructor(head, size) {
        this.head = null
        this.size = 0
    }
    _getNode(index) {
        if (index < 0 || index >= this.size) {
            throw new Error('越界了')
        }
        let currentNode = this.head
        for (let i = 0; i < index; i++) {
            currentNode = currentNode.next
        }
        return currentNode
    }
    
    add (index, ele) {
        if (arguments.length == 1) {
            ele = index
            index = this.size
        }
        if (index < 0 || index > this.size) {
            throw new Error('cross the border')
        }
        if (index == 0) {
            let head = this.head
            this.head = new Node(ele, head)
        } else {
            let prevNode = this._getNode(index - 1)
            prevNode.next = new Node(ele, prevNode.next)
        }
        this.size++
    }

    remove(index) {
        let reNode = null
        if (index == 0) {
            reNode = this.head 
            if (!reNode) return undefined
          this.head = reNode.next
        } else {
          let prevNode = this._getNode(index - 1)
          reNode = prevNode.next
          prevNode.next = reNode.next
        }
        this.size--
        return reNode
      }

      set(index, ele) {
        let node = this._getNode(index)
        node.ele = ele
      }
      get(index) {
        return this._getNode(index)
      }
      clear() {
        this.head = null 
        this.size = 0 
      }

}

class Queue{
    constructor() {
      this.linkedList = new LinkedList()
    }
    enQueue(data) {
      this.linkedList.add(data)
    }
    deQueue() {
      return this.linkedList.remove(0)
    }
  }
  

const link = new LinkedList()
link.add('node1')
link.add('node2')
link.add(1, 'node3')
// l1.remove(1)
link.set(1, 'node3-3')
// let a = l1.get(0)
// link.clear()
console.log(link)

// const q = new Queue()
// q.enQueue('node1')
// q.enQueue('node2')
// let a = q.deQueue()
// a = q.deQueue()
// a = q.deQueue()
// console.log(a)

